<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/6/19
 * Time: 19:26
 */
class Login extends CI_Controller{
    public function __construct(){
        parent::__construct();
        $this->load->helper('captcha');
        $this->load->library('form_validation');
    }
    public function login(){
        if($_POST){
            $this->form_validation->set_rules('username', '用户名', 'required');
            $this->form_validation->set_rules('password', '密码', 'required');
            #获取表单数据
            $captcha = strtolower($this->input->post('captcha'));
            #获取session中保存的验证码
            $code = strtolower($this->session->userdata('code'));
            if($code === $captcha){
                #验证码正确，则需要验证用户名和密码
                if ($this->form_validation->run() == false){
                    $data['message'] = validation_errors();
                    $data['url'] = site_url('Admin/Login/login');
                    $data['wait'] = 3;
                    $this->load->view('message.html',$data);
                } else{
                    $username = $this->input->post('username',true);
                    $password = $this->input->post('password',true);

                    if ($username == 'admin' && $password == '123'){
                        # OK，保存session信息,然后跳转到首页
                        $this->session->set_userdata('admin',$username);
                        redirect('Admin/Main/index');
                    } else{
                        # error
                        $data['url'] = site_url('Admin/Login/login');
                        $data['message'] = '用户名和密码错误，请重新填写';
                        $data['wait'] = 3;
                        $this->load->view('message.html',$data);
                    }
                }
            }else{
                #验证码不正确，给出提示页面，然后返回
                $data['url'] = site_url('Admin/Login/login');
                $data['message'] = '验证码错误，请重新填写';
                $data['wait'] = 3;
                $this->load->view('message.html',$data);
            }
        }else{
            $this->load->view('Login/login.html');
        }
    }

    public function code(){
        $vals = array(
            'img_width' => '140',
            'img_height' => '20',
        );
        $code = create_captcha($vals); //获取验证码
        $this->session->set_userdata('code',$code);
    }

    public function login_out(){
        $this->session->sess_destroy();
        redirect('Admin/Login/login');
    }
}